package com.sdx.console.crm.service;

import com.alibaba.fastjson.JSON;
import com.ibeetl.admin.core.service.RedisService;
import com.sdx.console.crm.entity.CrmMessage;
import com.sdx.console.crm.entity.CrmRepresentive;
import com.sdx.console.crm.entity.CrmSession;
import com.sdx.console.crm.web.WebSocketServer;
import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.db.KeyHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @ClassName CrmRepresentiveService
 * @Description: 坐席服务
 * @author: tanbaocai
 * @date: 2019/7/25 11:14
 */
@Service
public class CrmRepresentiveService {
	private static final Logger log = LoggerFactory.getLogger("statuScanner");
	private static final String SQL = "crm.scanner";
	//客户等待队列:1
	private static final String WAIT_QUEUE = "_crm_session_wait";
	@Resource
	private SQLManager sqlManager;

	@Resource
	private RedisService redisService;

	/**
	 * 关闭坐席
	 * @param
	 */
	@Transactional(rollbackFor = Exception.class)
	public void closeRepresentive(CrmRepresentive crmRepresentive) {
		Integer workId = crmRepresentive.getWorkId();
		Integer userId =crmRepresentive.getUserId();
		CrmSession sessionParam = new CrmSession();
		sessionParam.setUserId(userId);
		List<CrmSession> sessionList = sqlManager.select(SQL + ".selectMatchSessions", CrmSession.class, sessionParam);

		if (sessionList.size()>0) {
			CrmRepresentive param = new CrmRepresentive();
			param.setWorkId(workId);
			param.setStatusTime(new Date());
			param.setServiceStatus(4);
			sqlManager.updateTemplateById(param);
			param.setUserId(userId);
			sqlManager.update(SQL+".updateSessionStatus",param);
			releaseRepresentive(userId);
			for (int i = 0; i < sessionList.size(); i++) {
				try {

					//回到等待队列
					CrmSession session = sessionList.get(i);
					CrmMessage crmMessage = new CrmMessage();
					crmMessage.setSourceType(session.getSourceType());
					crmMessage.setAppId(session.getAppId());
					crmMessage.setCustomerId(session.getCustomerId());
					crmMessage.setOpenid(session.getOpenId());
					String jsonValue = JSON.toJSONString(crmMessage);
					String customerId = crmMessage.getCustomerId();
					if (!StringUtils.isEmpty(customerId) && !redisService.isSetMember("set" + WAIT_QUEUE + "_" +crmRepresentive.getTenantId(), customerId)) {
						redisService.jumpIn("list" + WAIT_QUEUE + "_" +crmRepresentive.getTenantId(), jsonValue);
						redisService.setSetValue("set" + WAIT_QUEUE + "_" +crmRepresentive.getTenantId(), customerId);
					} else if (StringUtils.isEmpty(customerId) && !StringUtils.isEmpty(crmMessage.getOpenid()) && !redisService.isSetMember("set" + WAIT_QUEUE + "_" +crmRepresentive.getTenantId(), crmMessage.getOpenid())) {
						redisService.jumpIn("list" + WAIT_QUEUE + "_" +crmRepresentive.getTenantId(), jsonValue);
						redisService.setSetValue("set" + WAIT_QUEUE + "_" +crmRepresentive.getTenantId(), crmMessage.getOpenid());
					}
				} catch (Exception e1) {
					log.error("session", e1);
				}
			}
		} else {
			Calendar calendar = Calendar.getInstance();
			calendar.add(Calendar.HOUR,-2);
			if (calendar.getTime().after(crmRepresentive.getLastOperTime())) {
				releaseRepresentive(userId);
			}
		}
	}

	/**
	 * 释放客服websocket和线程
	 * @param userId
	 */
	private void releaseRepresentive(Integer userId) {
		//TODO 释放客服websocket和线程
		WebSocketServer.removeWebSocket(userId);
	}

	public int insertCrmRepresentive(Integer userId,Integer tenantId){
		CrmRepresentive crmRepresentive = new CrmRepresentive();
		Date date = new Date();
		crmRepresentive.setUserId(userId);
		crmRepresentive.setStatusTime(date);
		crmRepresentive.setServiceStatus(1);
		crmRepresentive.setLastOperTime(date);
		crmRepresentive.setLoginTime(date);
		crmRepresentive.setTenantId(tenantId);
		KeyHolder keyHolder = new KeyHolder();
		sqlManager.insert(CrmRepresentive.class,crmRepresentive,keyHolder);
		int key = Integer.parseInt(keyHolder.getKey().toString());
		return key;
	}

}
